package pl.mchaniewski.ryneczek.web.user;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import pl.mchaniewski.ryneczek.pojo.Quotation;
import pl.mchaniewski.ryneczek.services.QuotationService;
import pl.mchaniewski.ryneczek.utilities.DateUtil;
import pl.mchaniewski.ryneczek.utilities.NavigationUtil;

@Component
@Scope("request")
@PreAuthorize("isAuthenticated()")
public class QuotationListBean {
    private static final Logger logger = LoggerFactory
            .getLogger(QuotationListBean.class);
    private QuotationService quotationService;
    private SelectedPortfolioBean selectedPortfolioBean;

    /* PostConstruct parameters */
    private List<Quotation> latestQuotations;

    @Autowired
    public void setQuotationService(QuotationService quotationService) {
        this.quotationService = quotationService;
    }

    @Autowired
    public void setSelectedPortfolioBean(
            SelectedPortfolioBean selectedPortfolioBean) {
        this.selectedPortfolioBean = selectedPortfolioBean;
    }

    public List<Quotation> getLatestQuotations() {
        return latestQuotations;
    }

    @PostConstruct
    public void init() {
        if (logger.isDebugEnabled()) {
            logger.debug("QuotationListBean is being initialized.");
        }
        if (selectedPortfolioBean.getSelectedPortfolioId() == null) {
            NavigationUtil.directRedirect(NavigationUtil.DIRECT_INDEX);
        }

        Date before = null;
        if (logger.isDebugEnabled()) {
            before = DateUtil.getNow();
        }

        latestQuotations = quotationService.findLatest(true);

        if (logger.isDebugEnabled()) {
            if (before != null) {
                long miliseconds = DateUtil.getNow().getTime()
                        - before.getTime();
                logger.debug("Total time in ms: {}", miliseconds);
            }
        }
    }

}
